package com.example.demo.controller;

import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import com.example.demo.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(originPatterns = "http://localhost:*")
public class FileUploadController {

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private StudentService studentService;

    /**
     * 上传学生头像
     *
     * @param file 文件
     * @param studentId 学生ID
     * @return 上传结果
     */
    @PostMapping("/avatar/upload")
    public Map<String, Object> uploadAvatar(@RequestParam("file") MultipartFile file,
                                            @RequestParam("studentId") Long studentId) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 上传文件到OSS
            String avatarUrl = ossUtil.uploadFile(file);
            if (avatarUrl == null) {
                result.put("code", 500);
                result.put("message", "文件上传失败");
                return result;
            }

            // 更新学生头像URL
            Student student = studentService.findById(studentId);
            if (student == null) {
                result.put("code", 404);
                result.put("message", "学生不存在");
                return result;
            }

            student.setAvatarUrl(avatarUrl);
            boolean success = studentService.save(student);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "头像上传成功");
                result.put("data", avatarUrl);
            } else {
                result.put("code", 500);
                result.put("message", "头像保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "头像上传失败：" + e.getMessage());
        }

        return result;
    }
}